# -*- coding: utf-8 -*-

from constants import *
from scipy import misc
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter

debug = False

if(debug):
    files = ["2007806Aug82008_1_05.jpg"]
else:
    files = os.listdir(file_dir)

variables = {}

for filen in files:

    print "Starting: " , filen
    x = misc.imread(file_dir+filen,flatten=True)
    # When converting from a colour image to black and white, the library uses the ITU-R 601-2 luma transform:    
    #image = image.filter(ImageFilter.FIND_EDGES)
    x = 255-x
    x = x * (x>offset)
    
    # start_x, start_Y
    # finner sentrum basert på vekt (skriv notat)
    sx = int(np.sum(x.transpose()[0:(x.shape[1]/2),:]*range(x.shape[0])) / np.sum(x[:,0:(x.shape[1]/2)]))
    sy = 4

    # -- gå fra venstre til første pixeltreff --
    # -- andre del unngår piksler som står alene --
    # .. og stopp om vi kommer halvveis
    while(((not x[sx,sy]) or np.sum(x[sx-1:sx+2,sy-1:sy+2])==x[sx,sy]) and sy<150):
        sy += 1
    
    if(sy==150):
        print "WARNING : " , filen, " Discarded due to miss"        
        continue
    broken = []
    # current_x, current_y
    cx, cy = sx, sy
    
    path = []
    #pathx = []
    #pathy = []
    #pathxy = []

    dp = np.array([[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]])
    d = 4   

    finished = False
    counter = 0
    
    while(not finished and counter<10):
        tt = tuple([cx,cy]+dp[d])
        if(x[tt]):
            path.append(d)
            #pathx.append(cx)
            #pathy.append(cy)
            #pathxy.append(tt)
            cx += dp[d][0]
            cy += dp[d][1]
            d = (d+2)%8
            counter = 0
            
            if(cx==sx and cy==sy):
                finished = True
        else:
            d = (d-1)%8
            counter += 1
        if(debug):
            print cx,cy
    if(finished):
        with open(result_dir+os.sep+"weights"+os.sep+filen[:-4], 'w') as f:
            f.write("".join(map(str,path))+os.sep)
    else:
        broken.append(filen)
        print "Warning: Failed to return to start!"

if(broken):
    with open(result_dir+os.sep+"Not_discretized", 'w') as f:
            f.write("\n".join(broken))
    

if(debug):
    x = x/4
    x[pathx,pathy] = 250
    plt.imshow(x,interpolation="none")
    plt.show()
       

    
            
        
        
    
        
    

    
